<template>
  <view class="container">
    <!-- 个人信息卡片 -->
    <view class="user-card" @click="viewPersonalInfo">
      <image
        class="avatar"
        :src="userInfo.avatar || '/static/logo.png'"
        mode="aspectFill"
      ></image>
      <view class="user-info">
        <text class="username">{{ userInfo.username || "游客用户" }}</text>
        <text class="user-desc">{{
          userInfo.email || "点击查看个人信息"
        }}</text>
      </view>
      <view class="arrow"></view>
    </view>

    <!-- 功能列表 -->
    <view class="menu-section">
      <view class="menu-item" @click="viewPersonalInfo">
        <view class="menu-icon">👤</view>
        <view class="menu-text">个人资料</view>
        <view class="menu-arrow"></view>
      </view>

      <view class="menu-item" @click="viewFavorites">
        <view class="menu-icon">⭐</view>
        <view class="menu-text">我的收藏</view>
        <view class="menu-arrow"></view>
      </view>

      <view class="menu-item" @click="viewSettings">
        <view class="menu-icon">⚙️</view>
        <view class="menu-text">设置</view>
        <view class="menu-arrow"></view>
      </view>
    </view>
  </view>
</template>

<script>
import { AuthService } from "../../utils/auth.js";

export default {
  data() {
    return {
      userInfo: {
        username: "城市游客",
        avatar: "",
        email: "",
        phone: "",
      },
    };
  },

  onShow() {
    // 监听用户信息更新事件
    uni.$on("userInfoUpdated", this.handleUserInfoUpdate);
    
    // 如果已经登录且有用户ID，重新获取用户信息
    // 这样当从personalInfo页面返回时，能显示最新的头像
    if (this.userInfo && this.userInfo.id) {
      console.log("页面显示，重新获取用户信息");
      this.getUserInfo();
    }
  },

  onUnload() {
    // 移除事件监听，避免内存泄漏
    uni.$off("userInfoUpdated", this.handleUserInfoUpdate);
  },
  async onLoad() {
    // 检查用户是否已登录
    await this.checkLoginStatus();
  },

  methods: {
    /**
     * 检查登录状态
     */
    async checkLoginStatus() {
      // 调用AuthService检查登录状态
      const isLoggedIn = AuthService.isAuthenticated();

      if (!isLoggedIn) {
        // 如果未登录，跳转到登录页面
        uni.navigateTo({
          url: "/pages/auth/login",
        });
      } else {
        // 如果已登录，获取用户信息
        await this.getUserInfo();
      }
    },

    /**
     * 获取用户信息
     */
    async getUserInfo() {
      try {
        // 从AuthService获取基础用户信息（包含id）
        const basicUserInfo = AuthService.getUserInfo();

        if (basicUserInfo && basicUserInfo.id) {
          // 如果有id，调用API获取详细用户信息
          const detailResponse = await this.fetchUserDetail(basicUserInfo.id);
          
          if (detailResponse && detailResponse.code === 200 && detailResponse.data) {
            // 更新用户信息，处理头像路径和默认值
            const detailedInfo = detailResponse.data;
            this.userInfo = {
              id: detailedInfo.id,
              username: detailedInfo.username || "城市游客",
              avatar: detailedInfo.avatar ? `http://192.168.126.1:9000/fznostalgia/user/${detailedInfo.avatar}` : "",
              email: detailedInfo.email || "",
              phone: detailedInfo.phone || "",
              status: detailedInfo.status,
              cityName: detailedInfo.cityName
            };
            // 更新存储的用户信息
            AuthService.setUserInfo(this.userInfo);
          } else {
            // 如果获取详细信息失败，使用基础信息
            this.userInfo = {
              username: basicUserInfo.nickname || basicUserInfo.username || "城市游客",
              avatar: basicUserInfo.avatar || "",
              email: "",
              phone: ""
            };
          }
        } else {
          // 如果无法获取用户信息，设置为默认值
          this.userInfo = {
            username: "城市游客",
            avatar: "",
            email: "",
            phone: ""
          };
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
        // 错误情况下设置默认值
        this.userInfo = {
          username: "城市游客",
          avatar: "",
          email: "",
          phone: ""
        };
      }
    },
    
    /**
     * 根据用户id获取详细信息
     * @param {number} userId - 用户ID
     * @returns {Promise<Object>} 详细用户信息
     */
    async fetchUserDetail(userId) {
      return new Promise((resolve, reject) => {
        const API_URL = `http://127.0.0.1:8687/admin/user/details-app/${userId}`;
        
        uni.request({
          url: API_URL,
          method: 'GET',
          header: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${AuthService.getToken()}`
          },
          timeout: 10000,
          success: (res) => {
            if (res.statusCode === 200) {
              resolve(res.data);
            } else {
              reject(new Error(`获取用户详情失败: ${res.statusCode}`));
            }
          },
          fail: (err) => {
            console.error('用户详情请求失败:', err);
            reject(err);
          }
        });
      });
    },
    viewPersonalInfo() {
      // 跳转到个人信息详情页，并传递用户信息
      uni.navigateTo({
        url: `/pages/mine/personalInfo?userInfo=${encodeURIComponent(JSON.stringify(this.userInfo))}`,
      });
    },
    viewFavorites() {
      uni.showToast({
        title: "我的收藏功能开发中",
        icon: "none",
      });
    },
    viewSettings() {
      uni.navigateTo({
        url: "/pages/mine/settings",
      });
    },

    // 处理用户信息更新
    handleUserInfoUpdate(newUserInfo) {
      console.log("收到用户信息更新", newUserInfo);
      
      // 如果更新了头像，重新请求后端获取最新信息
      if (newUserInfo.id && newUserInfo.avatarUpdated) {
        console.log("头像已更新，重新获取用户信息");
        this.getUserInfo();
      } else {
        // 否则直接更新本地信息
        this.userInfo = {
          id: newUserInfo.id,
          username: newUserInfo.username || newUserInfo.nickname || "城市游客",
          avatar: newUserInfo.avatar ? `http://192.168.126.1:9000/fznostalgia/user/${newUserInfo.avatar}` : "",
          email: newUserInfo.email || "",
          phone: newUserInfo.phone || "",
          status: newUserInfo.status,
          cityName: newUserInfo.cityName
        };
      }
    },
  },
};
</script>

<style scoped>
.container {
  padding: 0;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 用户信息卡片样式 */
.user-card {
  background: linear-gradient(135deg, #1a5f7a 0%, #3d8c9f 100%);
  padding: 40rpx;
  display: flex;
  align-items: center;
  color: white;
  margin-bottom: 20rpx;
  border-radius: 0 0 20rpx 20rpx;
}

.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  background-color: white;
  padding: 4rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.user-info {
  margin-left: 30rpx;
  flex: 1;
}

.username {
  font-size: 40rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.user-desc {
  font-size: 28rpx;
  opacity: 0.9;
}

.arrow {
  width: 0;
  height: 0;
  border-left: 12rpx solid white;
  border-top: 12rpx solid transparent;
  border-bottom: 12rpx solid transparent;
}

/* 功能菜单样式 */
.menu-section {
  background-color: white;
  border-radius: 20rpx;
  margin: 0 20rpx 20rpx;
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx 30rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.menu-item:active {
  background-color: rgba(61, 140, 159, 0.1);
}

.menu-item:last-child {
  border-bottom: none;
}

.menu-icon {
  font-size: 40rpx;
  margin-right: 30rpx;
  width: 40rpx;
  text-align: center;
}

.menu-text {
  flex: 1;
  font-size: 32rpx;
  color: #1a5f7a;
}

.menu-arrow {
  width: 0;
  height: 0;
  border-left: 12rpx solid #3d8c9f;
  border-top: 12rpx solid transparent;
  border-bottom: 12rpx solid transparent;
}

/* 响应式调整 */
@media screen and (min-width: 768px) {
  .container {
    max-width: 768rpx;
    margin: 0 auto;
  }
}
</style>
